package com.bnzj.core.webmvc.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.bnzj.core.rest.IResult;
import com.bnzj.core.rest.ResponseResult;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Tag(name = "QuartzController", description = "定时任务")
@RequestMapping("/sys/quartz")
public class QuartzController {

	@Resource
    private SchedulerFactoryBean schedulerFactoryBean;

	@Resource
	private Scheduler scheduler;

	@Operation(summary = "定时任务列表")
    @PostMapping(value = "/list")
    @ResponseBody
    public ResponseResult<Page<JobDetail>> list() throws SchedulerException {
        List<String> list = scheduler.getJobGroupNames();
        List<JobDetail> jobList = new ArrayList<JobDetail>(); 
        for (String group : list) {
            GroupMatcher<JobKey> matcher = GroupMatcher.groupEquals(group);
            Set<JobKey> set = scheduler.getJobKeys(matcher);
            for(JobKey jobKey : set) {
                jobList.add(scheduler.getJobDetail(jobKey));
            }
        }
        return ResponseResult.success(new PageImpl<JobDetail>(jobList));
    }

    @Operation(summary = "主动执行定时任务", description="主动执行定时任务")
    @PostMapping(value = "/{key}/execute")
    public IResult<String> execute(@Parameter(description = "任务Key") @PathVariable String key){
    	try {
        	JobKey jobKey = JobKey.jobKey(key);
        	scheduler.triggerJob(jobKey);
    		return ResponseResult.success();
		} catch (Exception e) {
			log.error("", e);
			return ResponseResult.success();
		}
    }
}
